<template>
  <el-card class="chat-container">
    <div slot="header" class="card-header">聊天室</div>

    <div class="message-box" ref="messageBox">
      <div v-for="(msg, index) in msgList" :key="index" class="message-item">
        <div :class="['message-content', getClass(msg)]">
          {{ getContent(msg) }}
          <span class="time">{{ formatTime(msg.time) }}</span>
        </div>
      </div>
    </div>

    <!-- 输入区域 -->
    <div class="input-area">
      <UserAvatar :src="currentUser.avatar" size="medium" />
      <el-input
        v-model="message"
        placeholder="输入消息..."
        @keyup.enter.native="sendMessage"
        style="flex: 1; margin: 0 10px;"
      />
      <el-button type="primary" @click="sendMessage">发送</el-button>
    </div>
  </el-card>
</template>

<script>
import UserAvatar from '@/components/UserAvatar.vue';

export default {
  name: 'Chat',
  components: { UserAvatar },
  data() {
    return {
      message: '',
      currentUser: {
        username: '',
        nickname: '',
        avatar: ''
      }
    };
  },
  computed: {
    msgList() {
      return this.$store.getters.getMsgList;
    }
  },
  mounted() {
    this.initUser();
    this.connectWebSocket();
  },
  beforeDestroy() {
    this.disconnectWebSocket();
  },
  methods: {
    initUser() {
      const userStr = sessionStorage.getItem('user');
      if (!userStr) {
        this.$router.push('/');
        return;
      }

      try {
        const userObj = JSON.parse(userStr);
        this.currentUser = {
          username: userObj.username || '',
          nickname: userObj.nickname || '',
          avatar: userObj.avatar || 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'
        };
      } catch (e) {
        console.error("Failed to parse user from session storage");
        this.$router.push('/');
      }
    },

    connectWebSocket() {
      const username = this.currentUser.username;

      if (!username) {
        this.$message.error('用户名为空，无法连接聊天室');
        return;
      }

      // 连接 WebSocket
      this.$websocket.connect(username);

      // 设置消息回调
      this.$websocket.onMessage((receivedMsg) => {
          console.log("【WebSocket 收到消息】", receivedMsg); // 👈 日志：收到的消息

          if (receivedMsg.systemMessageType === "FORBIDDEN_WORDS_UPDATE") {
              console.log("【系统消息】收到最新的违禁词列表:", receivedMsg.forbiddenWords); // 👈 日志
              this.$store.dispatch('updateForbiddenWords', receivedMsg.forbiddenWords);
          } else if (receivedMsg.userNames && Array.isArray(receivedMsg.userNames)) {
              const formattedUsers = receivedMsg.userNames.map(name => ({
                  username: name
              }));
              this.$store.dispatch('updateUserList', formattedUsers);
          } else {
              if (receivedMsg.from !== this.currentUser.username) {
                  this.$store.dispatch('addChatMessage', receivedMsg);
              }
          }
      });
    },

    disconnectWebSocket() {
      this.$websocket.disconnect();
    },

    sendMessage() {
      const { username } = this.currentUser;

      if (!this.message.trim()) {
        this.$message.warning('请输入内容');
        return;
      }

      // 获取当前 Vuex 中的违禁词列表并打印
      const forbiddenWords = this.$store.getters.getForbiddenWords.map(w => w.word);
      console.log("【违禁词检测】当前违禁词列表:", forbiddenWords); // 👈 日志
      console.log("【违禁词检测】用户输入的消息:", this.message); // 👈 日志

      const foundWord = forbiddenWords.find(word => this.message.includes(word));

      if (foundWord) {
        console.warn(`【违禁词拦截】发现敏感词：“${foundWord}”`); // 👈 日志
        this.$message.error(`不能发送包含敏感词：“${foundWord}”`);
        return;
      }

      const now = new Date();
      const time = `${now.getHours()}:${now.getMinutes() < 10 ? '0' + now.getMinutes() : now.getMinutes()}`;

      const message = {
        from: username,
        content: this.message,
        time: time,
        id: Date.now()
      };

      this.$websocket.sendMessage(message);
      this.msgList.push({ ...message });
      this.scrollToBottom();

      this.message = '';
    },

    scrollToBottom() {
      this.$nextTick(() => {
        const box = this.$refs.messageBox;
        if (box) {
          box.scrollTop = box.scrollHeight;
        }
      });
    },

    getClass(msg) {
      if (msg.systemMessage) {
        return 'system-message';
      } else if (msg.from === this.currentUser.username) {
        return 'self-message';
      } else {
        return 'other-message';
      }
    },

    getContent(msg) {
      return msg.content;
    },

    formatTime(timeStr) {
      const [h, m] = timeStr.split(':');
      return `${h.padStart(2, '0')}:${m.padStart(2, '0')}`;
    }
  }
};
</script>

<style scoped>
.card-header {
  font-weight: bold;
}

.message-box {
  height: 400px;
  overflow-y: auto;
  border: 1px solid #eee;
  padding: 10px;
  margin-bottom: 15px;
  display: flex;
  flex-direction: column;
}

.message-item {
  margin-bottom: 10px;
}

.message-content {
  padding: 8px 12px;
  line-height: 1.5;
  font-size: 14px;
  border-radius: 6px;
  word-break: break-word;
  width: fit-content;
  max-width: 60%;
}

/* 自己的消息 */
.self-message {
  background-color: #d9ebff;
  color: #333;
  border-radius: 6px 4px 6px 6px;
  text-align: left;
  margin-left: auto;
}

/* 对方的消息 */
.other-message {
  background-color: #f0f0f0;
  color: #333;
  border-radius: 4px 6px 6px 6px;
  text-align: left;
  margin-right: auto;
}

/* 系统消息 */
.system-message {
  align-self: center;
  background-color: transparent !important;
  color: #666;
  font-style: italic;
  width: auto;
  max-width: 80%;
  padding: 4px 12px;
  text-align: center;
  margin: 0 auto;
  border-radius: 4px;
  animation: fadeIn 0.3s ease-in-out;
}

.time {
  font-size: 12px;
  color: #999;
  margin-top: 4px;
  display: block;
}

.input-area {
  display: flex;
  align-items: center;
}
</style>